package com.baiduspring.service.user.impl;

import com.baiduspring.dao.entity.PrivateLetter;
import com.baiduspring.dao.mapper.PrivateLetterMapper;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.PrivateLetterService;
import com.baiduspring.vo.PrivateLetteVO;
import com.baiduspring.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 私信接口实现类
 *
 * @author xiongyan
 */
@Service
@Slf4j
public class PrivateLetterServiceImpl implements PrivateLetterService {
    @Resource
    private PrivateLetterMapper privateLetterMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PrivateLetteVO vo) {
        PrivateLetter privateLetter;
        try {
            privateLetter = vo.validate().conver(vo, new PrivateLetter());
        } catch (BaiduSpringException e) {
            log.error("数据验证失败", e);
            throw e;
        }

        privateLetter.setCreateDate(System.currentTimeMillis());
        privateLetter.setShow(0);

        try {
            privateLetterMapper.insertSelective(privateLetter);
        } catch (Exception e) {
            log.error("私信创建你错误：{}", e);
            throw new BaiduSpringException("私信发送异常");
        }
    }

    @Override
    public Integer getCount(Long account, Integer show) {
        PrivateLetter privateLetter = new PrivateLetter();
        privateLetter.setAddressee(account);
        privateLetter.setShow(show);
        return privateLetterMapper.count(privateLetter);
    }

    @Override
    public Optional<List<PrivateLetteVO>> getPrivateLetterLishByAddressee(Long account) {
        List<PrivateLetter> privateLetters = this.privateLetterMapper.selectByAddresseeOrderByCreateDateDesc(account);

        List<PrivateLetteVO> privateLetteVOS = privateLetters.stream().map(privateLetter -> {
            PrivateLetteVO vo = new PrivateLetteVO();
            BeanUtils.copyProperties(privateLetter, vo);

            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(privateLetter.getUser(), userVO);
            vo.setUserVO(userVO);
            return vo;
        }).collect(Collectors.toList());

        return Optional.ofNullable(privateLetteVOS);
    }

    @Override
    public void updateToAlreadyShow(Long id) {

    }
}
